#include "fileope.h"

//打开文件
FILE *openFile(const char *path, const char *mode)
{
	FILE *file = NULL;
	if (NULL != path && NULL != mode)
	{
		file = fopen(path, mode);
		if (NULL == file)
		{
			printf("open %s faield -> %s\n", path, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}
	else
	{
		printf("参数不对...\n");
		exit(EXIT_FAILURE);
	}
	return file;
}
//将用户列表保存到文件中
void saveUsrListToFile(const char *path, const UsrList *list)
{
	if (NULL == path || NULL == list)
	{
		return;
	}
	FILE *file = openFile(path, "wb");
	UsrNode *node = list->pFirstNode;
	while (NULL != node)
	{
		printf("name:%s, pwd:%s\n", node->caUsrName, node->caUsrPwd);
		fwrite(node, sizeof(UsrNode), 1, file);
		node = node->pNext;
	}
	fclose(file);
}
//将用户信息从文件中读取出来放到列表中
void loadUsrInfoFromFile(const char *path, UsrList *list)
{
	if (NULL == path || NULL == list)
	{
		return;
	}
	FILE *file = openFile(path, "rb");
	UsrNode *node = NULL;
	int ret = 0;
	while (1)
	{
		node = mkUsrNode();
		ret = fread(node, sizeof(UsrNode), 1, file);
		if (0 == ret)
		{
			free(node);
			node = NULL;
			if (feof(file))
			{
				break;
			}
			else if (ferror(file))
			{
				fclose(file);
				printf("read file error...\n");
				exit(EXIT_FAILURE);
			}
		}	
		node->pNext = NULL;
		insert(list, node);
	}
	fclose(file);
}





